<template>
  <el-form ref="genInfoForm" :model="info" :rules="rules" label-width="150px">
    <el-row>
      <el-col :span="12">
        <el-form-item prop="tplCategory">
          <template #label>生成模板</template>
          <el-select v-model="info.tplCategory" @change="tplSelectChange">
            <el-option label="单表（增删改查）" value="crud" />
            <el-option label="主子表（增删改查）" value="sub" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="tplWebType">
          <template #label>前端类型</template>
          <el-select v-model="info.tplWebType">
            <el-option label="Vue3 Element Plus 模版" value="element-plus" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="basePackageName">
          <template #label>
            <div class="flex flex-row items-center">
              <span class="mr-1">Java包基础路径</span>
              <el-tooltip content="生成在哪个java包下，例如 com.cetc.city.system" placement="top">
                <el-icon>
                  <question-filled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="info.basePackageName" @change="refreshPackageName" />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="packageName" label="Java包路径">
          <span>{{ info.packageName }}</span>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item prop="sysCode" label="子系统">
          <el-select placeholder="请选择子系统" v-model="info.sysCode" @change="changeSys">
            <el-option
              v-for="dict in gen_sys_list"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item prop="modelCode" label="功能模块">
          <el-select placeholder="请选择功能模块" v-model="info.modelCode" @change="changeModel">
            <el-option
              v-for="dict in modelList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-form-item prop="businessCode" label="业务模块">
          <el-select
            placeholder="请选择业务模块"
            v-model="info.businessCode"
            @change="changeBusiness"
          >
            <el-option
              v-for="dict in businessList"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item prop="encrypt" label="加密传输">
          <el-radio-group v-model="info.encrypt">
            <el-radio :value="true" label="是" />
            <el-radio :value="false" label="否" />
          </el-radio-group>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item prop="hmacVerify" label="请求校验">
          <el-radio-group v-model="info.hmacVerify">
            <el-radio :value="true" label="是" />
            <el-radio :value="false" label="否" />
          </el-radio-group>
        </el-form-item>
      </el-col>

      <el-col :span="8">
        <el-form-item prop="dataScope" label="数据权限">
          <el-radio-group v-model="info.dataScope">
            <el-radio :value="true" label="是" />
            <el-radio :value="false" label="否" />
          </el-radio-group>
        </el-form-item>
      </el-col>

      <el-col :span="12" v-if="info.dataScope === true">
        <el-form-item prop="deptIdField" label="部门字段">
          <el-select placeholder="请选择部门字段" v-model="info.deptIdField">
            <el-option
              v-for="(dict, index) in props.info.columns"
              :key="index"
              :label="`${dict.columnComment} ${dict.columnName}`"
              :value="dict.columnName"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="12" v-if="info.dataScope === true">
        <el-form-item prop="userIdField" label="用户字段">
          <el-select placeholder="请选择用户字段" v-model="info.userIdField">
            <el-option
              v-for="(dict, index) in props.info.columns"
              :key="index"
              :label="`${dict.columnComment} ${dict.columnName}`"
              :value="dict.columnName"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="seqName" label="序列名称">
          <el-input v-model="info.seqName" />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item prop="genType">
          <template #label>
            <div class="flex flex-row items-center">
              <span class="mr-1">生成代码方式</span>
              <el-tooltip content="默认为zip压缩包下载，也可以自定义生成路径" placement="top">
                <el-icon>
                  <question-filled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-radio-group v-model="info.genType">
            <el-radio value="0" label="zip压缩包" />
            <el-radio value="1" label="自定义路径" />
          </el-radio-group>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item class="w-full">
          <template #label>
            <div class="flex flex-row items-center">
              <span class="mr-1">上级菜单</span>
              <el-tooltip content="分配到指定菜单下，例如 系统管理" placement="top">
                <el-icon>
                  <question-filled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-tree-select
            v-model="info.parentMenuId"
            :data="menuOptions"
            :props="{ value: 'menuId', label: 'menuName', children: 'children' }"
            value-key="menuId"
            placeholder="请选择上级菜单"
            check-strictly
          />
        </el-form-item>
      </el-col>

      <el-col :span="24" v-if="info.genType === '1'">
        <el-form-item prop="genPath">
          <template #label>
            <div class="flex flex-row items-center">
              <span class="mr-1">自定义路径</span>
              <el-tooltip
                content="填写磁盘绝对路径，若不填写，则生成到当前Web项目下"
                placement="top"
              >
                <el-icon>
                  <question-filled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
          <el-input v-model="info.genPath" />
        </el-form-item>
      </el-col>
    </el-row>

    <template v-if="info.tplCategory === 'tree'">
      <h4 class="form-header">其他信息</h4>
      <el-row>
        <el-col :span="12">
          <el-form-item>
            <template #label>
              <div class="flex flex-row items-center">
                <span class="mr-1">树编码字段</span>
                <el-tooltip content="树显示的编码字段名， 如：dept_id" placement="top">
                  <el-icon>
                    <question-filled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-select v-model="info.treeCode" placeholder="请选择">
              <el-option
                v-for="(column, index) in info.columns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <template #label>
              <div class="flex flex-row items-center">
                <span class="mr-1">树父编码字段</span>
                <el-tooltip content="树显示的父编码字段名， 如：parent_Id" placement="top">
                  <el-icon>
                    <question-filled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-select v-model="info.treeParentCode" placeholder="请选择">
              <el-option
                v-for="(column, index) in info.columns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <template #label>
              <div class="flex flex-row items-center">
                <span class="mr-1">树名称字段</span>
                <el-tooltip content="树节点的显示名称字段名， 如：dept_name" placement="top">
                  <el-icon>
                    <question-filled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-select v-model="info.treeName" placeholder="请选择">
              <el-option
                v-for="(column, index) in info.columns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </template>

    <template v-if="info.tplCategory === 'sub'">
      <h4 class="form-header">关联信息</h4>
      <el-row>
        <el-col :span="12">
          <el-form-item>
            <template #label>
              <div class="flex flex-row items-center">
                <span class="mr-1">关联子表的表名</span>
                <el-tooltip content="关联子表的表名， 如：sys_user" placement="top">
                  <el-icon>
                    <question-filled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-select v-model="info.subTableName" placeholder="请选择" @change="subSelectChange">
              <el-option
                v-for="(table, index) in tables"
                :key="index"
                :label="table.tableName + '：' + table.tableComment"
                :value="table.tableName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <template #label>
              <div class="flex flex-row items-center">
                <span class="mr-1">子表关联的外键名</span>
                <el-tooltip content="子表关联的外键名， 如：user_id" placement="top">
                  <el-icon>
                    <question-filled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-select v-model="info.subTableFkName" placeholder="请选择">
              <el-option
                v-for="(column, index) in subColumns"
                :key="index"
                :label="column.columnName + '：' + column.columnComment"
                :value="column.columnName"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </el-form>
</template>

<script setup>
  import { ref, getCurrentInstance, defineProps, watch } from 'vue';
  import { listMenu } from '@/api/system/menu';
  import { getDicts } from '@/api/system/dict/data';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
    tables: {
      type: Array,
      default: () => [],
    },
  });

  const { proxy } = getCurrentInstance();
  const { gen_sys_list } = proxy.useDict('gen_sys_list');

  const modelList = ref([]);
  const businessList = ref([]);
  const menuOptions = ref([]);
  const subColumns = ref([]);

  const rules = ref({
    tplCategory: [{ required: true, message: '请选择生成模板', trigger: 'blur' }],
    basePackageName: [{ required: true, message: '请输入Java包基础路径', trigger: 'blur' }],
    sysCode: [{ required: true, message: '请选择子系统', trigger: 'blur' }],
    modelCode: [{ required: true, message: '请选择功能模块', trigger: 'blur' }],
    businessCode: [{ required: true, message: '请选择业务模块', trigger: 'blur' }],
    encrypt: [{ required: true, message: '请选择是否加密传输', trigger: 'blur' }],
    hmacVerify: [{ required: true, message: '请选择是否请求校验', trigger: 'blur' }],
    dataScope: [{ required: true, message: '请选择是否启用数据权限', trigger: 'blur' }],
    deptIdField: [{ required: true, message: '请选择部门字段', trigger: 'blur' }],
    userIdField: [{ required: true, message: '请选择用户字段', trigger: 'blur' }],
    seqName: [{ required: true, message: '请输入序列名称', trigger: 'blur' }],
  });

  watch(
    () => props.info.tplWebType,
    (val) => {
      if (!val) {
        props.info.tplWebType = 'element-plus';
      }
    },
  );

  watch(
    () => props.info.subTableName,
    (val) => {
      setSubTableColumns(val);
    },
  );

  const firstInit = watch(
    () => props.info.sysCode,
    (v) => {
      if (v) {
        initModelList();
        initBusinessList();
        firstInit();
      }
    },
  );

  function subSelectChange() {
    props.info.subTableFkName = '';
  }

  function tplSelectChange(value) {
    if (value !== 'sub') {
      props.info.subTableName = '';
      props.info.subTableFkName = '';
    }
  }

  function setSubTableColumns(value) {
    for (let item in props.tables) {
      const name = props.tables[item].tableName;
      if (value === name) {
        subColumns.value = props.tables[item].columns;
        break;
      }
    }
  }

  function changeSys(v) {
    props.info.sysName = gen_sys_list.value.find((item) => item.value === v).label;

    props.info.modelCode = '';
    props.info.modelName = '';
    modelList.value = [];

    props.info.businessCode = '';
    props.info.businessName = '';
    businessList.value = [];

    initModelList();
    refreshPackageName();
  }

  function changeModel(v) {
    props.info.modelName = modelList.value.find((item) => item.dictValue === v).dictLabel;

    props.info.businessCode = '';
    props.info.businessName = '';
    businessList.value = [];

    initBusinessList();
    refreshPackageName();
  }

  function changeBusiness(v) {
    props.info.businessName = businessList.value.find((item) => item.dictValue === v).dictLabel;

    refreshPackageName();
  }

  function initModelList() {
    const { sysCode } = props.info;
    if (sysCode) {
      getDicts(`gen_sys_item_${sysCode}`).then((res) => {
        modelList.value = res.data;
      });
    }
  }

  function initBusinessList() {
    const { sysCode, modelCode } = props.info;
    if (sysCode && modelCode) {
      getDicts(`gen_business_item_${sysCode}_${modelCode}`).then((res) => {
        businessList.value = res.data;
      });
    }
  }

  function refreshPackageName() {
    props.info.packageName = `${props.info.basePackageName}.${props.info.sysCode}.${props.info.modelCode}.${props.info.businessCode}`;
  }

  function getMenuTreeselect() {
    listMenu().then((res) => {
      menuOptions.value = proxy.handleTree(
        res.data.map((k) => ({
          ...k,
          menuId: `${k.menuId}`,
          parentId: `${k.parentId}`,
        })),
        'menuId',
      );
    });
  }

  getMenuTreeselect();
</script>
